package com.qf.courtesycard.provide.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qf.courtesyard.domain.vo.ResultVo;
import com.qf.courtesycard.provide.entity.Ticket;
import com.qf.courtesycard.provide.service.ITicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lx
 * @since 2023-03-10
 */
@RestController
@RequestMapping("/provide")
@Slf4j
public class TicketController {

    @Autowired
    private ITicketService ticketService;

    /**
     * 生成优惠券
     *
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/createTicket")
    public ResultVo createTicket() throws JsonProcessingException {
        ticketService.createTicket();
        return ResultVo.ok();
    }


//    @RequestMapping("/updateTicket")
//    public String updateTicket(Ticket ticket) {
//
//        String msg = ticketService.updateStatusById(ticket);
//
//        return null;
//    }

    /**
     * 发放优惠券
     *
     * @return
     */

    @RequestMapping("/distributeTicket")
    @HystrixCommand(fallbackMethod = "fallback",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "30000")
            },
            threadPoolKey = "ticketpool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "5"),
                    @HystrixProperty(name = "maxQueueSize", value = "5")
            })
    public ResultVo distributeTicket() throws Exception {

        Ticket ticket = ticketService.distributeTicket();
        ResultVo ok = ResultVo.ok();
        ok.put("data", ticket);
        return ok;
    }



    @RequestMapping("/updateTicket")
    public ResultVo updateTicket(Ticket ticket) {
        String msg = ticketService.updateStatusById(ticket);
        ResultVo ok = ResultVo.ok();
        ok.put("msg", msg);
        return ok;
    }


    public ResultVo fallback() {
        log.debug("抢券失败！");
        return ResultVo.ok();
    }

}
